package model

import "time"

type Channel struct {
	Id int64 `xorm:"pk autoincr"`
	Suffix string
	StatisticsDateList []*StatisticsDate `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Browse struct {
	Id int64 `xorm:"pk autoincr"`
	UserId int64
	ChannelId int64
	ChannelName string
	ViewsNumber int
	CreatedAt time.Time
	UpdatedAt time.Time
}

type SingUp struct {
	Id int64 `xorm:"pk autoincr"`
	NickName string
	Sex string
	Age int
	Phone int16
	ChannelId int64
	ChannelName string
	RegistrationTime time.Time
	CreatedAt time.Time
	UpdatedAt time.Time
}

type StatisticsDate struct {
	TotalDate string
	Views int
	VisitorsNumber int
	ApplicantsNumber int
	ConversionRate int
}

func Statistics(cIdList []int, sdList []string)([]*Channel, error){

	var cs []*Channel

	for _, cv := range cIdList{
		var c Channel
		x.Id(cv).Get(&c)
		for _, sdv := range sdList{

			var sd StatisticsDate
			sd.TotalDate = sdv

			bTotal, err := x.Where("channel_id = ?", c.Id).And("created_at = ?", sdv).Count(new(Browse))
			if err != nil{
				return nil, err
			}
			sd.VisitorsNumber = int(bTotal)

			bSum, sErr := x.Where("channel_id = ?", c.Id).And("created_at = ?", sdv).SumInt(new(Browse), "views_number")
			if sErr != nil{
				return nil, sErr
			}
			sd.Views = int(bSum)

			sTotal, tErr := x.Where("channel_id = ?", c.Id).And("registration_time = ?", sdv).Count(new(SingUp))
			if tErr != nil{
				return nil, tErr
			}
			sd.ApplicantsNumber = int(sTotal)

			sd.ConversionRate = sd.ApplicantsNumber/sd.VisitorsNumber

			c.StatisticsDateList = append(c.StatisticsDateList, &sd)

		}
		cs = append(cs, &c)
	}

	return cs, nil
}
